<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <input id="search-word" />
    <ul id="suggestions"></ul>
    <script>
      function jsonp(options) {
        return new Promise((resolve, reject) => {
          const { url, jsonp, data } = options;
          let callbackName = `jQuery_${Date.now()}`;
          window[callbackName] = function (data) {
            delete window[callbackName];
            document.body.removeChild(script);
            resolve(data);
          };
          let script = document.createElement("script");
          let queryStr = url.indexOf("?") === -1 ? "?" : "&";
          for (let key in data) {
            queryStr += `${key}=${data[key]}&`;
          }
          script.src = `${url}${queryStr}${jsonp}=${callbackName}`;
          script.onerror = (error) => reject(error);
          document.body.appendChild(script);
        });
      }
      let searchWord = document.getElementById("search-word");
      let suggestions = document.getElementById("suggestions");
      searchWord.addEventListener("input", (event) => {
        let wd = event.target.value;
        jsonp({
          url: "https://www.baidu.com/sugrec",
          jsonp: "cb",
          data: {
            prod: "pc",
            wd,
          },
        })
          .then((result) => {
            let { g } = result;
            if (g) {
              let html = "";
              for (let i = 0; i < g.length; i++) {
                html += `<li>${g[i].q}</li>`;
              }
              suggestions.innerHTML = html;
            }
          })
          .catch((error) => {
            console.log(error);
          });
      });
    </script>
  </body>
</html>
